package com.zs4sdk;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Message;
import android.view.View;

import com.zs4sdk.activity.login.Zs4GameLoginActivity;
import com.zs4sdk.dialog.VerifyIdCardDialog;
import com.zs4sdk.activity.Zs4GameNoticeActivity;
import com.zs4sdk.common.Extra;
import com.common.library.data.CommonEventHandler.ResultHandlerInEvent;
import com.common.library.data.CommonHandle;
import com.common.library.data.CommonHandle.HandleMessage;
import com.common.library.data.EventHandler2Get;
import com.zs4sdk.entity.Zs4GameData;
import com.zs4sdk.entity.LoginJSONResultEntity;
import com.zs4sdk.entity.MenuItemJSONResultEntity;
import com.zs4sdk.entity.UpdateJSONResultEntity;
import com.zs4sdk.entity.VersionJSONResultEntity;
import com.zs4sdk.extra.Zs4GameCode;
import com.zs4sdk.extra.Zs4GameInfo;
import com.zs4sdk.extra.Zs4GameUserInfo;
import com.common.library.listener.OnProcessListener;
import com.zs4sdk.receiver.SDKGameProcessReceiver;
import com.zs4sdk.service.SDKGameMenuService;
import com.common.library.util.ActivityHelper;
import com.common.library.util.ChannelUtil;
import com.common.library.util.DialogUtils;
import com.common.library.util.FileUtils;
import com.common.library.util.HandlerUtil;
import com.common.library.util.Helper;
import com.common.library.util.JsonHelper;
import com.common.library.util.LogUtil;
import com.common.library.util.NetworkHelper;
import com.common.library.util.ParamsHelper;
import com.common.library.util.PreferencesHelper;
import com.common.library.util.ProjectHelper;
import com.common.library.util.permission.FloatWindowManager;
import com.common.library.widget.SDKGameStartMenu;
import com.zs4sdk.common.Zs4GameUtil;
import com.zs4sdk.statistics.Zs4GameStatistics;

/**
 * function: 提供接口给外部调用
 *
 * @ author: aXiBa
 */
public class Zs4GameBase {

    public static final String TAG = Zs4GameBase.class.getSimpleName();

    // //////////////////////////////////////////////////////////////////////////
    // 对外常量
    // //////////////////////////////////////////////////////////////////////////

    public static final int SCREEN_ORIENTATION_LANDSCAPE = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;   // 横屏
    public static final int SCREEN_ORIENTATION_PORTRAIT = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;   // 竖屏
    public static final int SCREEN_ORIENTATION_SENSOR_LANDSCAPE = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;   // 横屏(支持sensor)
    public static final int SCREEN_ORIENTATION_SENSOR_PORTRAIT = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;   // 竖屏(支持sensor)

    //  悬浮菜单初始化停靠位置
    public static final int DUCKPOSITION_LEFTTOP = 1;
    public static final int DUCKPOSITION_LEFTBOTTOM = 2;
    public static final int DUCKPOSITION_RIGHTTOP = 3;
    public static final int DUCKPOSITION_RIGHTBOTTOM = 4;

    /**
     * intent key
     */
    public static final String KEY_ORDER_CODE = "ordercode";
    public static final String KEY_ADSID = "ads_id";
    public static final String KEY_GOODS_ID = "goodsid";
    public static final String KEY_CP_ORDER_ID = "cp_order_id";
    public static final String FORMAT_TIME_STAMP = "yyyyMMddHHmmssSSS";
    public static final String MENUITEM_NAME = "MENUITEM_NAME";
    public static final String KEY_PAY_URL = "NNPAYURL";
    public static final String TPYE = "key_type";
    public static final String ERROR_MESSAGE = "key_error_message";


    private static boolean showWelcomeToast;
    private static boolean showLogo;
    VerifyIdCardDialog verifyIdCardDialog;


    // //////////////////////////////////////////////////////////////////////////
    // 对外方法
    // //////////////////////////////////////////////////////////////////////////


    /**
     * function: 初始化: ActivityHelper, 包名, 用户信息, 屏幕方向, 设备报到
     *
     * @param info
     * @ author: aXiBa 2013-3-5 下午5:22:27
     */
    public void init(Zs4GameInfo info, OnProcessListener listener) {
        // 初始化ActivityHelper
        ActivityHelper.init(info.getCtx().getApplicationContext());

        Zs4GameData.getInstance().setCanShowWelcomeToast(false);

        // 包名
        String appPackageName = info.getCtx().getApplicationContext().getPackageName();
        LogUtil.i(TAG, "当前包名: " + appPackageName);
        Zs4GameData.getInstance().setPackage_name(appPackageName);

        // 初始化app信息
        Zs4GameData.getInstance().setAppId(info.getAppId());
        Zs4GameData.getInstance().setAppKey(info.getAppKey());


        String channel= ChannelUtil.getChannel(info.getCtx());
        Zs4GameTD.InitSDK(info.getCtx(), channel);


        Zs4GameData.getInstance().setCompany(1);

        creatApkDir();

        // 清除以前的callback和监听
        clearCallbackAndListener();

        // 注册消息接收者
        registerMessageReceiver();

        // 启动服务
        Zs4GameMenu.startService(info.getCtx(), appPackageName);

        // 检查更新
        checkUpdateVersion(info.getCtx(), listener);


        //调用显示悬浮按钮
        showLogoButton(info.getCtx());
    }

    private static void creatApkDir(){
        //创建下载apk的路径目录
        String path = FileUtils.getInternalCacheDir().concat("sdkapk");
        Date time = new Date();
        File f=new File(path);
        if(f.exists()){
            FileUtils.deleteDir(path);
        }
    }
    /**
     * 取得当前时间戳
     *
     * @return
     */
    private long getTimestamp() {
        return System.currentTimeMillis() / 1000L;
    }

    /**
     * function:  设置屏幕方向
     *
     * @param mScreenOrientation
     * @ author: aXiBa 2013-3-6 上午9:01:32
     */
    public void setScreenOrientation(int mScreenOrientation) {
        Zs4GameData.getInstance().setScreen_orientation(mScreenOrientation);
    }


    /**
     * function: 得到屏幕方向
     *
     * @return
     * @ author: aXiBa 2013-3-6 上午9:30:40
     */
    public static int getScreen_orientation() {

        int screen_orientation = Zs4GameData.getInstance().getScreen_orientation();


        // 未定义的话，默认成横屏
        if (screen_orientation != SCREEN_ORIENTATION_LANDSCAPE
                && screen_orientation != SCREEN_ORIENTATION_PORTRAIT
                && screen_orientation != SCREEN_ORIENTATION_SENSOR_LANDSCAPE
                && screen_orientation != SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
            return SCREEN_ORIENTATION_LANDSCAPE;
        } else {
            return screen_orientation;
        }
    }

    private boolean isSetPlayerInfo = false;
    private boolean isSetServerInfo = false;


    public void setPlayerAndServerInfo(String playerId, String playerName, int playerLevel, String servId, String servName) {

        Zs4GameData.getInstance().setPlayerId(playerId);
        Zs4GameData.getInstance().setPlayerName(playerName);
        Zs4GameData.getInstance().setPlayerLevel(String.valueOf(playerLevel));
        isSetPlayerInfo = true;

        Zs4GameData.getInstance().setServId(servId);
        Zs4GameData.getInstance().setServName(servName);
        isSetServerInfo = true;

        // 上传充值的用户信息
        setUserInfoForPay();
    }

    /**
     * function: 设置服务器信息
     *
     * @param servId
     * @param servName
     * @ author: aXiBa 2013-4-15 上午11:53:05
     */
    public void setServerInfo(String servId, String servName) {

        Zs4GameData.getInstance().setServId(servId);
        Zs4GameData.getInstance().setServName(servName);

        isSetServerInfo = true;

        // 上传充值的用户信息
        setUserInfoForPay();
    }


    /**
     * function: 设置玩家信息
     *
     * @param playerId
     * @param playerName
     * @ author: aXiBa 2013-4-15 上午11:53:20
     */
    public void setPlayerInfo(String playerId, String playerName, int playerLevel) {

        Zs4GameData.getInstance().setPlayerId(playerId);
        Zs4GameData.getInstance().setPlayerName(playerName);
        Zs4GameData.getInstance().setPlayerLevel(String.valueOf(playerLevel));

        isSetPlayerInfo = true;

        // 上传充值的用户信息
        setUserInfoForPay();
    }


    /**
     * function: 设置支付额外信息
     *
     * @param data
     * @ author: aXiBa 2013-4-15 上午11:53:20
     */
    public void setPayExpandData(String data) {

        Zs4GameData.getInstance().setPayExpandData(data);
    }


    /**
     * function: 显示悬浮菜单
     *
     * @ author: aXiBa 2013-3-7 上午10:47:08
     */
    DialogUtils dialogUtils;
    public void showLogoButton(final Context ctx) {
        if (FloatWindowManager.getInstance().checkPermission(ctx)) {
//            Zs4GameData.getInstance().setShowLogoButon(true);
//            Zs4GameMenu.startMenu(ctx);
        } else {
            FloatWindowManager.getInstance().applyPermission(ctx);
        }
    }

    protected Zs4GameBase(){

    }
    /**
     * function: 隐藏悬浮菜单
     *
     * @param ctx
     * @ author: aXiBa 2013-3-31 下午4:34:53
     */
    public void hiddenLogoButton(Context ctx) {

        Zs4GameData.getInstance().setShowLogoButon(false);

        Zs4GameMenu.hiddenStartMenu(ctx);
    }

    /**
     * function: 设置悬浮菜单初始化位置
     *
     * @param duckPosition
     * @ author: aXiBa 2013-10-16 下午1:24:18
     */
    public void setLogoButtonInitDuckPosition(int duckPosition) {

        Zs4GameData.getInstance().setInitDuckPositionForLogoButton(duckPosition);
    }

    /**
     * function: 通知菜单屏幕方向改变
     *
     * @ author: aXiBa 2013-3-22 上午11:21:06
     */
    public void notifyMenuScreenOrientationChange(Context ctx) {

        Zs4GameMenu.notifyMenuScreenOrientationChange(ctx);
    }


    /**
     * function: 隐藏切换账号
     *
     * @ author: aXiBa 2013-11-8 下午2:23:50
     */
    public void hideSwitchAccount() {
        Zs4GameData.getInstance().setHiddenSwitchAccount(true);
    }


    /**
     * function: 取得用户信息
     *
     * @return
     * @ author: aXiBa 2013-3-6 上午9:21:54
     */
    public Zs4GameUserInfo getUserInfo() {
        if (this.isLogined()) {
            return Zs4GameData.getInstance().getSDKUserInfo();
        } else {
            return null;
        }
    }


    /**
     * function: 是否已登录
     *
     * @return
     * @ author: aXiBa 2013-3-19 上午12:40:51
     */
    public boolean isLogined() {
        return Zs4GameData.getInstance().isLogined();
    }


    /**
     * function: 得到单例
     *
     * @return
     * @ author: aXiBa 2013-3-5 下午5:08:31
     */
    public static Zs4GameBase getInstance() {
        if (sInstance == null) {
            sInstance = new Zs4Game();
        }
        return sInstance;
    }


    /**
     * function: 得到包名
     *
     * @ author: aXiBa 2013-3-22 上午11:22:46
     */
    public static String getPackageName() {

        return Zs4GameData.getInstance().getPackage_name();
    }


    /**
     * function: 设置调试模式
     *
     * @param isDebug
     * @ author: aXiBa 2013-4-1 下午1:03:45
     */
    public void setDebugMode(boolean isDebug) {
        Zs4GameData.getInstance().setDebug(isDebug);
    }


    /**
     * function: 得到版本信息
     *
     * @return
     * @ author: aXiBa 2013-3-6 上午9:18:52
     */
    public String getVersion() {

        return Extra.VERSION;
    }


    /**
     * function: 结束
     *
     * @ author: aXiBa 2013-3-18 下午7:08:24
     */
    public void finish(Context ctx) {

        // 保存用户悬浮菜单最后停放的位置
        if (SDKGameMenuService.isInitMenu()) {
            PreferencesHelper.getInstance(Extra.Preferences.SDKGAME_PFRFILE_USER_CONFIG).putInt(Extra.Preferences.SDKGAME_KEY_LASTDUCHPOSITION, SDKGameStartMenu.getmDuckType());
        }

        // stop服务
        Zs4GameMenu.stopService(ctx);

        Zs4GameData.getInstance().setShowLogoButon(false);

        Zs4GameData.clearInstance();

        clearCallbackAndListener();
    }


    /**
     * function:
     *
     * @ author: aXiBa 2013-12-5 下午6:07:10
     */
    private void clearCallbackAndListener() {

        if (Helper.isNotEmpty(mMessageCallbackList)) {
            mMessageCallbackList.clear();
        }

        if (Helper.isNotEmpty(mListenerList)) {
            Iterator<Entry<String, SDKGameProcessReceiver>> ite = mListenerList.entrySet().iterator();
            while (ite.hasNext()) {
                Entry<String, SDKGameProcessReceiver> entry = ite.next();
                SDKGameProcessReceiver item = entry.getValue();
                if (null != item) {
                    ActivityHelper.getGlobalApplicationContext().unregisterReceiver(item);
                }
            }
            mListenerList.clear();
        }
    }


    /**
     * function: 设置消息回调
     *
     * @param mListener
     * @ author: aXiBa 2013-4-9 上午10:40:52
     */
    public void setMessageCallBack(OnProcessListener mListener) {

        if (Helper.isNull(mMessageCallbackList)) {
            mMessageCallbackList = new ArrayList<OnProcessListener>();
        }

        if (Helper.isNotNull(mListener) && !mMessageCallbackList.contains(mListener)) {
            mMessageCallbackList.add(mListener);
        }

        registerReceiverSDK_logout(mListener);
    }


    /**
     * function: 移除消息回调
     *
     * @param mListener
     * @ author: aXiBa 2013-4-12 上午10:04:56
     */
    public void removeMessageCallBack(OnProcessListener mListener) {

        if (Helper.isNull(mMessageCallbackList)) {
            mMessageCallbackList = new ArrayList<OnProcessListener>();
        }

        if (Helper.isNotNull(mListener) && mMessageCallbackList.contains(mListener)) {
            mMessageCallbackList.remove(mListener);
        }
    }


    /**
     * function: 是否显示日志
     *
     * @ author: aXiBa 2013-4-15 上午11:53:20
     */
    public void setShowLog(boolean isShowLog) {

        Zs4GameData.getInstance().setShowLog(isShowLog);
    }

    /**
     * function: 是否显示toast欢迎信息
     *
     * @ author:lijupeng 2014-12-24 上午08:53:20
     */
    public void setShowWelcomeToast(boolean isShowWecomeToast) {

        Zs4GameData.getInstance().setShowWelcomeToastForCustom(isShowWecomeToast);
    }

    // //////////////////////////////////////////////////////////////////////////
    // 独立模块调用的方法
    // //////////////////////////////////////////////////////////////////////////


    /**
     * function: 显示菜单
     *
     * @param ctx
     * @ author: aXiBa 2013-7-11 下午3:35:16
     */
    public void showMenu(Context ctx) {

        Zs4GameMenu.showGridMenu(ctx, Extra.FLAG_MANUAL_MENU);
    }


    /**
     * function: 登录
     *
     * @param ctx
     * @param listener
     * @ author: aXiBa 2013-4-15 下午4:08:56
     */
    public void login(final Context ctx,final OnProcessListener listener) {

        // 注册登录广播接收
        final String action = getPackageName().concat(Extra.ACTIONKEY.LOGIN_POSTFIX);
        registerReceiver(action, listener);

        // 隐藏悬浮菜单
        Zs4GameMenu.hiddenStartMenu(ctx);

        // 1.7.0.1:判断是否已经登录(解决：很多游戏在登录页面就显示菜单，是自动分配的账号时会登录两次)
        if (Zs4GameBase.getInstance().isLogined()) {
            ActivityHelper.sendBroadcast(action, Zs4GameCode.LOGINSUCCESS, Zs4GameCode.LOGINTYPE_EMAIL, ctx);
            Zs4GameMenu.closeActivitysAndShowStartMenu(ctx, action);
        } else {
            // 验证最后一次登录账号
            LoginJSONResultEntity lastLoginedUserInfo = Zs4GameData.getInstance().getLastLoginedUserInfo();
            if (Helper.isNotNull(lastLoginedUserInfo)) {
                    verifyForLastLoginAccount(ctx, lastLoginedUserInfo, action);
            } else {
                goLoginOrRegister(ctx, action);
            }
        }
    }


    /**
     * function: 到登录或者注册页面
     *
     * @param ctx
     * @ author: aXiBa 2013-12-12 下午12:01:16
     */
    protected void goLoginOrRegister(Context ctx, String action) {

            HashMap<String, String> params = new HashMap<String, String>();
            params.put(Extra.INTENTKEY.BACKSENDMESSAGE, Extra.BOOLEAN_TRUE);
            Zs4GameMenu.startActivity(ctx, Zs4GameLoginActivity.class, action, params);
    }


    /**
     * function: 验证最后登录账号
     *
     * @param ctx
     * @param lastUserInfo
     * @param action
     * @ author: aXiBa 2013-12-4 下午3:08:05
     */
    protected void verifyForLastLoginAccount(final Context ctx, LoginJSONResultEntity lastUserInfo, final String action) {

//        LogUtil.e("=====",lastUserInfo.getNickName());
        // 请求最后登录账号信息
        if (NetworkHelper.isNetworkAvailable(ActivityHelper.getGlobalApplicationContext())) {
            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.SHOWPROCESS_FORACTIVITY, ctx);
            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
            String url =   Extra.URL.CHECKLOGIN;
            new EventHandler2Get(
                    url,
                    paramList,
                    ParamsHelper.getUserAgent1(),
                    new ResultHandlerInEvent() {

                        @Override
                        public void doResultHanler(JSONObject result) throws JSONException {
                            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS_FORACTIVITY);

                            Message msg = myHandle.obtainMessage();
                            msg.what = Extra.MessageKey.REQUESTCOMPLETE_LASTLOGINACCOUNT;
                            msg.obj = ctx;
                            Bundle bundle = new Bundle();
                            bundle.putString("param1", action);
                            bundle.putString("param2", result.toString());

                            msg.setData(bundle);

                            // 发送消息
                            myHandle.sendMessage(msg);
                        }

                        @Override
                        public void doExceptionHandler() {
                            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS_FORACTIVITY);
                            sendErrorMessage(ctx, action);
                        }
                    });
        } else {
            ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
            sendErrorMessage(ctx, action);
        }
    }


    /**
     * function: 发送错误信息
     *
     * @param ctx
     * @param action
     * @ author: aXiBa 2013-12-23 下午6:10:15
     */
    protected void sendErrorMessage(Context ctx, String action) {

        ActivityHelper.sendBroadcast(action, Zs4GameCode.ERROR, ctx);
        Zs4GameMenu.closeActivitysAndShowStartMenu(ctx, action);
    }


    /**
     * function: 注销
     *
     * @param ctx
     * @param listener
     * @ author: aXiBa 2013-4-15 下午4:08:56
     */
    public void logout(Context ctx, OnProcessListener listener) {

        // 注册广播接收
        String action = getPackageName().concat(Extra.ACTIONKEY.LOGOUT_POSTFIX);
        registerReceiver(action, listener);

        Zs4GameMenu.logoutHandle(ctx, action, getPackageName(),ActivityHelper.getString(ActivityHelper.getStringResId( "zs4gamestring_hint_logout_success")));
        Zs4GameUtil.clearLoginStatus(ctx);
                ;
    }

    public void registerReceiverSDK_logout(OnProcessListener listener){
        //注销
        String action = getPackageName().concat(Extra.ACTIONKEY.LOGOUT_POSTFIX);
        registerReceiver(action, listener);

        //充值
        String action1 = getPackageName().concat(Extra.ACTIONKEY.VOUCHERCENTER_POSTFIX);
        registerReceiver(action1, listener);
    }


    /**
     * function: 充值中心
     *
     * @param ctx
     * @param listener
     * @ author: aXiBa 2013-4-15 下午5:20:33
     */
//    public void enterVoucherCenter(Context ctx, OnProcessListener listener) {
//
//        // 注册充值中心广播接收
//        String action = getPackageName().concat(Extra.ACTIONKEY.VOUCHERCENTER_POSTFIX);
//        registerReceiver(action, listener);
//
//        Zs4GameMenu.enterVoucherCenter(ctx, action, getPackageName(), "","");
//    }


    /**
     * function: 支付中心
     *
     * @param ctx
     * @param good_code 商品代码
     * @param listener
     * @ author: aXiBa 2013-5-15 上午11:58:54
     */
    public void enterPaymentCenter(Context ctx, String good_code,String cp_order_id, int price,int count,OnProcessListener listener) {

        // 注册支付中心广播接收
        String action = getPackageName().concat(Extra.ACTIONKEY.VOUCHERCENTER_POSTFIX);
        registerReceiver(action, listener);

        Zs4GameMenu.enterVoucherCenter(ctx, action, getPackageName(), good_code,cp_order_id,price,count);
    }


    // //////////////////////////////////////////////////////////////////////////
    // 内部变量和方法
    // //////////////////////////////////////////////////////////////////////////

    private static Zs4GameBase sInstance;

    // 模块回调
    private static HashMap<String, SDKGameProcessReceiver> mListenerList = new HashMap<String, SDKGameProcessReceiver>();

    // 消息回调
    private static ArrayList<OnProcessListener> mMessageCallbackList = new ArrayList<OnProcessListener>();
    private OnProcessListener mMessageListener;


    /**
     * function: 注册广播
     *
     * @param action
     * @param listener
     * @ author: aXiBa 2013-3-18 下午2:46:31
     */
    protected void registerReceiver(String action, OnProcessListener listener) {

        if (!mListenerList.containsKey(action)) {
            SDKGameProcessReceiver receiver = new SDKGameProcessReceiver(action, listener);
            IntentFilter filter = new IntentFilter();
            filter.addAction(action);

            ActivityHelper.getGlobalApplicationContext().registerReceiver(receiver, filter);
            mListenerList.put(action, receiver);
        }
    }


    /**
     * function: 移除
     *
     * @param action
     * @ author: aXiBa 2013-3-19 上午12:38:39
     */
    private void removeReceiver(String action) {
        if (Helper.isNotEmpty(mListenerList)) {
            if (mListenerList.containsKey(action)) {
                ActivityHelper.getGlobalApplicationContext().unregisterReceiver(mListenerList.get(action));
                mListenerList.remove(action);
            }
        }
    }


    /**
     * function: 检查更新版本
     *
     * @ author: aXiBa 2013-3-26 下午4:14:13
     */
    private void checkUpdateVersion(final Context ctx, OnProcessListener listener) {

        // 注册初始化广播接收
        final String action = getPackageName().concat(Extra.ACTIONKEY.INIT_POSTFIX);
        registerReceiver(action, listener);

        if (NetworkHelper.isNetworkAvailable(ActivityHelper.getGlobalApplicationContext())) {
            Zs4GameData.getInstance().setUpdateMenuing(true);

            new EventHandler2Get(
                    Extra.URL.UPDATEAPI,
                    ParamsHelper.getUpdateVersionParame(),
                    ParamsHelper.getUserAgent1(),
                    new ResultHandlerInEvent() {

                        @Override
                        public void doResultHanler(JSONObject result) throws JSONException {
                            LogUtil.i(TAG, "更新结果： " + result);
                            if (Helper.isNotNull(result)) {
                                UpdateJSONResultEntity entity = new UpdateJSONResultEntity(result);

                                // 版本
                                if (UpdateJSONResultEntity.TYPE_UPDATE_VERSION.equals(entity.getType())) {

                                    menuCompleteHandle();
                                    saveMenuInfo(entity.getMenuEntityList(), entity.getLastupdate());

                                    Message msg = myHandle.obtainMessage();
                                    msg.what = Extra.MessageKey.VERSION_UPDATE;
                                    msg.obj = ctx;

                                    VersionJSONResultEntity versionEntity = entity.getVersionEntity();
                                    Bundle bundle = new Bundle();
                                    bundle.putString("title", versionEntity.getTitle());
                                    bundle.putString("content", versionEntity.getContent());
                                    bundle.putString("updateUrl", versionEntity.getUrl());
                                    bundle.putString("updateType", versionEntity.getForceupdate());
                                    msg.setData(bundle);

                                    myHandle.sendMessage(msg);
                                } else if (UpdateJSONResultEntity.TYPE_UPDATE_MENU.equals(entity.getType())) {

                                    // 保存菜单信息
                                    saveMenuInfo(entity.getMenuEntityList(), entity.getLastupdate());

                                    menuCompleteHandle();

                                    // 显示公告
                                    if (Extra.BOOLEAN_TRUE.equals(entity.getIs_notice())) {
                                        HandlerUtil.sendMessage(myHandle, Extra.MessageKey.HANDLE_SHOWNOTICE, ctx);
                                    } else {
                                        sendInitCompleteMessge(ctx);
                                    }
                                }
                                // 公告
                                else if (Extra.BOOLEAN_TRUE.equals(entity.getIs_notice())) {

                                    menuCompleteHandle();

                                    HandlerUtil.sendMessage(myHandle, Extra.MessageKey.HANDLE_SHOWNOTICE, ctx);
                                } else {
                                    menuCompleteHandle();

                                    sendInitCompleteMessge(ctx);
                                }
                            } else {
                                menuCompleteHandle();

                                sendInitCompleteMessge(ctx);
                            }
                        }

                        @Override
                        public void doExceptionHandler() {
                            menuCompleteHandle();

                            sendInitErrorMessge(ctx, ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_hint_http_request_fail")));
                        }
                    });
        } else {
            sendInitErrorMessge(ctx, ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network")));
        }
    }


   protected CommonHandle myHandle = new CommonHandle(ActivityHelper.getGlobalApplicationContext(), new HandleMessage() {

        @Override
        public void doHandleMessage(Message msg) {

            // 版本更新
            if (Extra.MessageKey.VERSION_UPDATE == msg.what) {

                Context ctx = (Context) msg.obj;
                Bundle bundle = msg.getData();
                String title = bundle.getString("title");
                String content = bundle.getString("content");
                String updateUrl = bundle.getString("updateUrl");
                String updateType = bundle.getString("updateType");
                updateVersionHandler(ctx, updateType, title, content, updateUrl);
            }
            // 显示公告
            else if (Extra.MessageKey.HANDLE_SHOWNOTICE == msg.what) {
                Zs4GameMenu.startActivity((Context) msg.obj, Zs4GameNoticeActivity.class, "", null);
            }
            // 最后账号登录成功
            else if (Extra.MessageKey.REQUESTCOMPLETE_LASTLOGINACCOUNT == msg.what) {
               final Context ctx = (Context) msg.obj;
                String action = "";
                String jsonResult = "";
                Bundle bundle = msg.getData();
                if (null != bundle) {
                    action = bundle.getString("param1");
                    jsonResult = bundle.getString("param2");
                }
                LoginJSONResultEntity entity = new LoginJSONResultEntity(jsonResult);
                if (Helper.isNotNull(entity) && entity.isSuccess()) {

                    // 设备验证失败, 清空密码让用户重新登录
                    if (!Extra.BOOLEAN_TRUE.equals(entity.getVerify())) {
//                        ActivityHelper.showToast(entity.getDesc());

                        Zs4GameData.getInstance().clearLoginInfo();
                        Zs4GameData.getInstance().clearLastLoginUserInfo();

                        goLoginOrRegister(ctx, action);
                    }
                    // 设备验证成功
                    else {

                        // 同步本地自动分配信息
                        Zs4GameMenu.synLocalAutoAssignInfo(entity);

                        Zs4GameData.getInstance().setLoginFirstTime(1);

                        Zs4GameData.getInstance().saveUserLoginInfoForLoginedSuccess(entity);

//						ProjectHelper.setUmengEvent(ctx, Extra.UMENGEVENG.KEY_YDLOGIN, Extra.UMENGEVENG.NAME_YDLOGIN);

//                        ActivityHelper.sendBroadcast(action, Zs4GameCode.LOGINSUCCESS, Zs4GameCode.LOGINTYPE_EMAIL, ctx);

                        Zs4GameMenu.closeActivitysAndShowStartMenu(ctx, action);
                        if(!entity.isVerify()) {
                            try {
                                final String finalAction = action;
                                verifyIdCardDialog = new VerifyIdCardDialog(ctx, false, new VerifyIdCardDialog.VerifyIdCardDialogListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (ActivityHelper.getIdResId("zs4gameviewid_mLeftView_view_titlebar") == view.getId() ||
                                                ActivityHelper.getIdResId("zs4gameviewid_btn_verify_id_nexttime") == view.getId()) {
                                            ActivityHelper.sendBroadcast(finalAction, Zs4GameCode.LOGINSUCCESS, Zs4GameCode.LOGINTYPE_EMAIL, ctx);
                                            verifyIdCardDialog.dismiss();
                                        }
                                    }
                                });
                                verifyIdCardDialog.show();
                            } catch (Exception e) {
                                e.printStackTrace();
                                ActivityHelper.sendBroadcast(action, Zs4GameCode.LOGINSUCCESS, Zs4GameCode.LOGINTYPE_EMAIL, ctx);
                            }
                        }else {
                            ActivityHelper.sendBroadcast(action, Zs4GameCode.LOGINSUCCESS, Zs4GameCode.LOGINTYPE_EMAIL, ctx);
                        }
                        Zs4GameMenu.startMenu(ctx);
                    }

                }
                // 登录失败
                else {
                    ActivityHelper.showToast(entity.getDesc());
                    Zs4GameData.getInstance().clearLoginInfo();
                    Zs4GameData.getInstance().clearLastLoginUserInfo();
                    sendErrorMessage(ctx, action);
                    goLoginOrRegister(ctx, action);
                }
            }
        }
    });


    /**
     * function: 菜单更新完成处理
     *
     * @ author: aXiBa 2013-4-3 下午4:47:31
     */
    private void menuCompleteHandle() {

//        Zs4GameData.getInstance().setUpdateMenuing(false);
////        LogUtil.i(TAG, "正在更新菜单...设置为false");
//
//        // 发送更新菜单完成广播
//        Intent intent = new Intent(getPackageName().concat(Extra.ACTIONKEY.UPDATEMENUCOMPLETE_POSTFIX_MENU));
//        ActivityHelper.getGlobalApplicationContext().sendBroadcast(intent);
    }


    /**
     * function: 注册消息接收
     *
     * @ author: aXiBa 2013-4-9 下午4:37:24
     */
    private void registerMessageReceiver() {

        mMessageListener = new OnProcessListener() {

            @Override
            public void finishProcess(int code, Bundle bundle) {
                if (Helper.isNotEmpty(mMessageCallbackList)) {
                    for (int i = 0; i < mMessageCallbackList.size(); i++) {
                        OnProcessListener itemProcess = mMessageCallbackList.get(i);
                        if (null != itemProcess) {
                            itemProcess.finishProcess(code, bundle);
                        }
                    }
                }
            }
        };
        registerReceiver(getPackageName().concat(Extra.ACTIONKEY.MESSAGE_POSTFIX), mMessageListener);
    }


    /**
     * function: 更新版本处理
     *
     * @param ctx
     * @param updateType
     * @param title
     * @param content
     * @param updateUrl
     * @ author: aXiBa 2013-3-27 下午7:01:12
     */
    private void updateVersionHandler(final Context ctx, String updateType, String title, String content, String updateUrl) {

        // 提示更新
        if (VersionJSONResultEntity.UPDATETYPE_ALERT.equals(updateType)) {
            AlertDialog.Builder tDialog = new AlertDialog.Builder(ctx);
            tDialog.setTitle(title);
            tDialog.setMessage(content);
            tDialog.setCancelable(false);
            tDialog.setPositiveButton(ctx.getString(ActivityHelper.getStringResId("zs4gamestring_btn_confirm")),
                    new OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            sendInitCompleteMessge(ctx);
                        }
                    });
            tDialog.show();
        }
        // 普通更新
        else if (VersionJSONResultEntity.UPDATETYPE_NORMAL.equals(updateType)) {

            recommendUpdateVersionHandler(title, content, updateUrl, ctx);
        }
        // 强制更新
        else if (VersionJSONResultEntity.UPDATETYPE_FORCE.equals(updateType)) {

            forceUpdateVersionHandler(title, content, updateUrl, ctx);
        } else {
            sendInitCompleteMessge(ctx);
        }
    }


    /**
     * function: 推荐版本更新处理
     *
     * @param title
     * @param content
     * @param updateUrl
     * @param ctx
     * @ author: aXiBa 2013-3-28 上午11:47:26
     */
    private void recommendUpdateVersionHandler(String title, String content, final String updateUrl, final Context ctx) {

        ActivityHelper.showAlertDialog(ctx,
                0,
                title,
                content,
                false,
                ActivityHelper.getStringResId("zs4gamestring_btn_confirm"),
                new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        executeUpdateVersion(updateUrl, ctx, Zs4GameCode.INITCOMPLETE);
                    }
                },
                ActivityHelper.getStringResId("zs4gamestring_btn_cancel"),
                new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        sendInitCompleteMessge(ctx);
                    }
                });
    }


    /**
     * function: 强制版本更新处理
     *
     * @param title
     * @param content
     * @param updateUrl
     * @param ctx
     * @ author: aXiBa 2013-3-28 上午11:47:51
     */
    private void forceUpdateVersionHandler(String title, String content, final String updateUrl, final Context ctx) {
        ActivityHelper.showAlertDialog(ctx, 0, title, content, false,

                new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        executeUpdateVersion(updateUrl, ctx, Zs4GameCode.UPDATEVERSION_FORCE_DOWNING);
                    }
                });
    }


    /**
     * function: 执行更新
     *
     * @param updateUrl
     * @param ctx
     * @param code
     * @ author: aXiBa 2013-3-29 下午5:59:14
     */
    private void executeUpdateVersion(String updateUrl, Context ctx, int code) {

        ActivityHelper.gotoDownload(ctx,"游戏更新下载安装",updateUrl,null,false);
//        if (FileUtils.hasSDCard()) {
//
//            // 下载
//            ProjectHelper.downApkWithBrowse(updateUrl, ctx);
//
//            ActivityHelper.sendBroadcast(Zs4GameData.getInstance().getPackage_name().concat(Extra.ACTIONKEY.INIT_POSTFIX),
//                    code, ctx);
//        } else {
//            // 更新版本，没有SD卡
//            ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_downnewapk_down_fail_sdcard"));
//            ActivityHelper.sendBroadcast(Zs4GameData.getInstance().getPackage_name().concat(Extra.ACTIONKEY.INIT_POSTFIX),
//                    Zs4GameCode.UPDATEVERSION_UNMOUNTED_SDCARD, ctx);
//        }
    }


    /**
     * function: 发送初始化错误消息
     *
     * @ author: aXiBa 2013-7-11 上午11:45:09
     */
    private void sendInitErrorMessge(Context ctx, String msg) {

        Bundle bundle = new Bundle();
        bundle.putString(ERROR_MESSAGE, msg);
        ActivityHelper.sendBroadcast(Zs4GameData.getInstance().getPackage_name().concat(Extra.ACTIONKEY.INIT_POSTFIX),
                Zs4GameCode.ERROR, ctx, bundle);

    }


    /**
     * function: 发送初始化完成消息
     *
     * @ author: aXiBa 2013-7-11 上午11:45:09
     */
    private void sendInitCompleteMessge(Context ctx) {

        ActivityHelper.sendBroadcast(Zs4GameData.getInstance().getPackage_name().concat(Extra.ACTIONKEY.INIT_POSTFIX),
                Zs4GameCode.INITCOMPLETE, ctx);
    }

    /**
     * function: 保存菜单信息
     *
     * @param menuList
     * @ author: aXiBa 2013-3-28 上午11:09:00
     */
    private void saveMenuInfo(ArrayList<MenuItemJSONResultEntity> menuList, String lastupdate) {
//
//        // 排序
//        Collections.sort(menuList, new SortBySeq());
//
//        // 保存信息
//        PreferencesHelper.getInstance().putString(Extra.Preferences.SDKGAME_KEY_MENUINFO, EncryptHelper.encryptByRC4(menuList.toString()));
//
//        // 保存时间
        saveMenuLastUpdate(lastupdate);
    }


    /**
     * function: 保存菜单lastupdate
     *
     * @param str
     * @ author: aXiBa 2013-3-28 上午9:45:02
     */
    private void saveMenuLastUpdate(String str) {

        long lastupdate = 1L;
        if (Helper.isNotEmpty(str)) {
            try {
                lastupdate = Long.parseLong(str);
            } catch (Exception e) {
            }
        }
        PreferencesHelper.getInstance().putLong(Extra.Preferences.SDKGAME_KEY_LASTUPDATE_MENU, lastupdate);
    }


    /**
     * function: 菜单排序
     *
     * @ author: aXiBa
     */
    class SortBySeq implements Comparator<MenuItemJSONResultEntity> {

        @Override
        public int compare(MenuItemJSONResultEntity lhs, MenuItemJSONResultEntity rhs) {

            int lSeq = Integer.parseInt(lhs.getSeq());
            int rSeq = Integer.parseInt(rhs.getSeq());

            return lSeq > rSeq ? 1 : -1;
        }

    }


    /**
     * function: 发送启动信息
     *
     * @ author: aXiBa 2013-4-7 下午6:23:11
     */
    private void sendLanuchInfo() {

        if (NetworkHelper.isNetworkAvailable(ActivityHelper.getGlobalApplicationContext())) {

            // 发送离线报道
            String offlineLanuchInfo = PreferencesHelper.getInstance(Extra.Preferences.SDKGAME_PFRFILE_PROJECT_CONFIG).getString(Extra.Preferences.SDKGAME_KEY_LANUCH_INFO);
            if (Helper.isNotEmpty(offlineLanuchInfo)) {
//				LogUtil.i(TAG, "发送离线启动信息: " + offlineLanuchInfo);
                ProjectHelper.sendAppStartInfo(JsonHelper.simpleEncode(offlineLanuchInfo));
                PreferencesHelper.getInstance(Extra.Preferences.SDKGAME_PFRFILE_PROJECT_CONFIG).putString(Extra.Preferences.SDKGAME_KEY_LANUCH_INFO, "");
            }

            // 发送在线报道
            ProjectHelper.sendAppStartInfo("");
        }
        // 没有网络，保存离线启动信息
        else {
            String offlineLanuchInfo = PreferencesHelper.getInstance(Extra.Preferences.SDKGAME_PFRFILE_PROJECT_CONFIG).getString(Extra.Preferences.SDKGAME_KEY_LANUCH_INFO);
//			LogUtil.i(TAG, "处理前离线启动信息: " + offlineLanuchInfo);
            String[] array = offlineLanuchInfo.split("\\|");
            HashMap<String, Integer> lanuchInfo = new HashMap<String, Integer>();
            if (Helper.isNotNull(array) && array.length > 0) {
                for (int i = 0; i < array.length; i++) {
                    String[] itemArray = array[i].split(",");
                    if (Helper.isNotNull(itemArray) && itemArray.length == 2) {
                        lanuchInfo.put(itemArray[0], Integer.parseInt(itemArray[1]));
                    }
                }
            }

            String curTime = Helper.date2String("yyyy-MM-dd");
            if (lanuchInfo.containsKey(curTime)) {
                lanuchInfo.put(curTime, lanuchInfo.get(curTime) + 1);
            } else {
                lanuchInfo.put(curTime, 1);
            }

            StringBuffer result = new StringBuffer();
            if (Helper.isNotEmpty(lanuchInfo)) {
                Iterator<Entry<String, Integer>> ite = lanuchInfo.entrySet().iterator();
                while (ite.hasNext()) {
                    Entry<String, Integer> entry = ite.next();
                    result.append(entry.getKey()).append(",").append(entry.getValue());
                    result.append("|");
                }
            }

            String resultStr = result.toString();
            if (resultStr.endsWith("|")) {
                resultStr = resultStr.substring(0, resultStr.lastIndexOf("|"));
            }

//			LogUtil.i(TAG, "处理后离线启动信息: " + resultStr);
            PreferencesHelper.getInstance(Extra.Preferences.SDKGAME_PFRFILE_PROJECT_CONFIG).putString(Extra.Preferences.SDKGAME_KEY_LANUCH_INFO, resultStr);
        }
    }


    /**
     * function: 设置充值的用户信息
     *
     * @ author: aXiBa 2013-5-13 上午11:22:27
     */
    private void setUserInfoForPay() {

        if (isSetServerInfo && isSetPlayerInfo) {
            Zs4GameTD.setUserInfo(ActivityHelper.getGlobalApplicationContext(), Zs4GameData.getInstance().getUserId(), Zs4GameData.getInstance().getPlayerId(),
                    Zs4GameData.getInstance().getPlayerName(),Integer.parseInt(Zs4GameData.getInstance().getPlayerLevel()),
                    Zs4GameData.getInstance().getServId(), Zs4GameData.getInstance().getServName());

                            isSetPlayerInfo = false;
                            isSetServerInfo = false;
        }
    }

    //独立客服入口
    public void showCustomerService(Context context){
        Zs4GameMenu.showWebView(context,
                "在线客服",
                Extra.URL.SDKGAME_FEEDBACK,
                null,
                "3");
    }



    //=====================================生命周期
    public void onCreate(Context context) {
        LogUtil.i("zs4gameGame-Activity-Life","onCreate");

    }
    public void onResume(Context context) {
        if(isLogined()) {
            Zs4GameMenu.startMenu(context);
        }else {
            hiddenLogoButton(context);
        }
        LogUtil.i("zs4gameGame-Activity-Life","onResume");
    }

    public void onPause(Context context) {
        LogUtil.i("zs4gameGame-Activity-Life","onPause");

    }

    public void onStop(Context context) {
        hiddenLogoButton(context);
        Zs4GameData.getInstance().setCanShowWelcomeToast(false);
        LogUtil.i("zs4gameGame-Activity-Life","onStop");
    }

    public void onDestroy(Context context) {
        LogUtil.i("zs4gameGame-Activity-Life","onDestroy");

    }

    public void onRestart(Context context) {
        if(isLogined()) {
            Zs4GameMenu.startMenu(context);
        }else {
            hiddenLogoButton(context);
        }
        Zs4GameData.getInstance().setCanShowWelcomeToast(true);
        LogUtil.i("zs4gameGame-Activity-Life","onRestart");

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtil.i("zs4gameGame-Activity-Life","onActivityResult");

    }

    public void onNewIntent(Intent intent) {
        LogUtil.i("zs4gameGame-Activity-Life","onNewIntent");

    }
    DialogUtils dialog;
    public void onBackPressed(final Context context) {
        LogUtil.i("zs4gameGame-Activity-Life","onBackPressed");
        dialog = new DialogUtils(context,
                ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_dialog_ensure_exit"))+ ActivityHelper.getApplicationName()+"?",
                ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_btn_confirm")),
                ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_btn_cancel")),
                new DialogUtils.LeaveDialogListener() {
                    @Override
                    public void onClick(View view) {
                        int id = view.getId();
                        if (ActivityHelper.getIdResId("zs4gameviewid_dialog_btn_cannel") == id) {
                            dialog.dismiss();
                        }
                        if (ActivityHelper.getIdResId("zs4gameviewid_dialog_btn_sure") == id) {
                            dialog.dismiss();
                            Zs4GameBase.getInstance().finish(context);
                            System.exit(0);
                            Zs4GameStatistics.exitSdk();
                        }
                    }
                });
        dialog.show();
    }

    public void onStart(Context context) {
        //在游戏Activity中的onRestart中调用
        LogUtil.i("zs4gameGame-Activity-Life","onStart");

    }

    public void onConfigurationChanged(Configuration newConfig) {
        LogUtil.i("zs4gameGame-Activity-Life","onPause");
    }

    //=====================================

    public void onExitzs4gameGame(Context context){
        onBackPressed(context);
    }


}



